package cn.bugstack.config;

import cn.bugstack.trigger.listener.OrderPaySuccessListener;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Configuration
public class GuavaConfig {

    @Bean(name = "weixinAccessToken")
    public Cache<String, String> weixinAccessToken() {
        return CacheBuilder.newBuilder()
                .expireAfterWrite(2, TimeUnit.HOURS)
                .build();
    }

    @Bean(name = "openidToken")
    public Cache<String, String> openidToken() {
        return CacheBuilder.newBuilder()
                .expireAfterWrite(1, TimeUnit.HOURS)
                .build();
    }

    @Bean
    public EventBus eventBusListener(OrderPaySuccessListener listener){
        EventBus eventBus = new EventBus();
        eventBus.register(listener);
        return eventBus;
    }


//    public BeanPostProcessor eventBusSubscriberProcessor(EventBus eventBus) {
//        return new BeanPostProcessor() {
//            public Object postProcessAfterInitialization(Object bean, String beanName) {
//                if(hasSubscribeMethods(bean)){
//                    eventBus.register(bean);
//                }
//                return bean;
//            }
//            private boolean hasSubscribeMethods(Object bean) {
//                return Arrays.stream(bean.getClass().getMethods()).anyMatch(method -> method.isAnnotationPresent(Subscribe.class));
//            }
//        };
//    }

}
